# coding: utf-8

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import os
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageEnhance
from handler.image import *

# 切割字符
def cut(img, i):
    width, height = img.size
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    pixdata = img.load()
    top, edge, image_data_array = [], [], []
    '''判断左右边界'''
    judge = 0
    for n in xrange(width):
        count = 0
        for j in xrange(height):
            if pixdata[n, j] == BLACK:
                if judge == 0:
                    edge.append(n)
                    judge = 1
                    count = 1
                    break
                if judge == 1:
                    count += 1
        if judge == 1 and count == 0:
            edge.append(n - 1)
            judge = 0
    if len(edge) == 7:
        edge.append(width - 1)
    '''判断上下边界'''
    for k in range(4):
        judge = 0
        for j in xrange(height):
            count = 0
            for n in xrange(edge[2 * k], edge[2 * k + 1] + 1):
                if pixdata[n, j] == BLACK:
                    if judge == 0:
                        top.append(j)
                        judge = 1
                        count = 1
                        break
                    if judge == 1:
                        count += 1
            if judge == 1 and count == 0:
                top.append(j - 1)
                break
        box = (edge[2 * k], top[2 * k], edge[2 * k + 1] + 1, top[2 * k + 1])
        xim = img.crop(box)
        xim.save('/home/yehun/%d_%d.bmp' % (i, k))
        image_data_array.append(xim)
    return image_data_array

# 中值滤波
def remove_noise(img,window=1):
    window_x = []
    window_y = []
    if window == 1:
        # 十字形
        window_x = [1,0,0,-1,0]
        window_y = [0,1,0,0,-1]
    elif window == 2:
        # 3*3矩阵型
        window_x = [-1,0,1,-1,0,1,1,-1,0]
        window_y = [-1,-1,-1,1,1,1,0,0,0]
    elif window == 3:
        # 5*5矩阵型
        for i in range(-2,3):
            for j in range(-2,3):
                window_x.append(i)
                window_y.append(j)
    width,height = img.size
    pixdata = img.load()
    BLACK = (0,0,0)
    WHITE = (255,255,255)
    color = [WHITE,BLACK]
    # temp = []
    for i in xrange(width):
        # temp.append([])
        for j in xrange(height):
            box = []
            jump = False
            black_count,white_count = 0,0
            for k in xrange(len(window_x)):
                d_x = i + window_x[k]
                d_y = j + window_y[k]
                try:
                    is_black = pixdata[d_x, d_y] == BLACK
                    box.append(int(is_black))
                    if is_black:
                        black_count += 1
                    else:
                        white_count += 1
                except IndexError:
                    pixdata[i,j] = WHITE
                    # temp[i].append(color[0])
                    jump = True
                    break
            box.sort()
            if jump == False:
                pixdata[i,j] = color[box[(len(box))/2]]


image_url = 'http://query.sinosig.com/lifeInsurance/servlet/VerifyCode?type=adminLogin'
# image_url = 'http://service.cpic.com.cn/common/generateCaptcha?1516336380426'
image = download_to_image(image_url)
# image_grey=image.convert('L')#灰度化
# image_peak=image_grey.convert('1')#二值化
# image_filter = image_peak.filter(ImageFilter.MedianFilter)
# for i in range(10):
#     image_filter = image_filter.filter(ImageFilter.MedianFilter)
# code = image_to_string(image_filter)
# print(code)
# image.show()
# image_grey.show()
# # image_peak.show()
# image_filter.show()


binaryzation(image,150)
# image.show()
# remove_line(image)
# image_rmeove_interfere(image)
# remove_noise(image, 3)
code = image_to_string(image)
print(code)
# print(cut(image,0))
image.show()